package VIEWS;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import CONTROLLERS.KhoaControllers;
import ModelEntityFW.KhoaEntity;
import ModelEntityFW.UserEntitys;
import Ultils.*;

import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.Font;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

public class frmKhoa extends JFrame {

	private JPanel contentPane;
	// private final ButtonGroup buttonGroup = new ButtonGroup();
	private JButton capNhat;
	private JButton ghiFile;
	private JButton lamMoi;
	private JButton close;
	// private JTable table;
	private JTable tableData_1;
	private static Connection m_objConnections;
	private KhoaControllers m_objControllers;
	private static UserEntitys m_objSecurityContext;
	// private static frmKhoa fKhoa;
	private KhoaEntity m_objKhoa;
	private static boolean bFlag = false;
	private DefaultTableModel obj_DTM;
	private JScrollPane scrollPane;
	private JButton btnXa;
	private JButton btnThmKhoa;

	/**
	 * Launch the application.
	 */
	/*
	 * public static void main(String[] args) { EventQueue.invokeLater(new
	 * Runnable() { public void run() { try { frmKhoa frame = new frmKhoa();
	 * frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }
	 * }); }
	 */

	/**
	 * Create the frame.
	 */
	public frmKhoa(Connection objConnection, UserEntitys objSecurity) {
		m_objConnections = objConnection;
		m_objSecurityContext = objSecurity;
		m_objKhoa = new KhoaEntity();
		obj_DTM = new DefaultTableModel();
		tableData_1 = new JTable();
		m_objControllers = new KhoaControllers(m_objConnections, m_objSecurityContext);
		
		
		setIconImage(Toolkit.getDefaultToolkit().getImage(frmKhoa.class.getResource("/images/3_2.png")));
		setTitle("Khoa");
		setResizable(false);
		
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 755, 351);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(0, 0, 749, 45);
		contentPane.add(toolBar);

		capNhat = new JButton("Cập nhật [!]");
		capNhat.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(bFlag){
					//Object obj=new Object();
					Vector<String> itemTenNV = frmEditKhoa.setItemJCC(m_objConnections);
					m_objKhoa.setbFlag(bFlag);
					m_objKhoa.setMaKhoa(String.valueOf(obj_DTM.getValueAt(tableData_1.getSelectedRow(), 0)));
					m_objKhoa.setTenKhoa(String.valueOf(obj_DTM.getValueAt(tableData_1.getSelectedRow(), 1)));
					m_objKhoa.setSoLuong(String.valueOf(obj_DTM.getValueAt(tableData_1.getSelectedRow(), 2)));
					String temp = String.valueOf(obj_DTM.getValueAt(tableData_1.getSelectedRow(), 3));
					for (String string : itemTenNV) {
						if(temp.equals(string)){
							m_objKhoa.setMaNhanVien(""+itemTenNV.indexOf(string));
						}
					}
					
					bFlag=false;
					frmEditKhoa f_EditKhoa = new frmEditKhoa(m_objConnections, m_objSecurityContext, m_objKhoa);
					f_EditKhoa.setVisible(true);
					LoadData(true);
					//dispose();
				}else{
					JOptionPane.showMessageDialog(getParent(), "Vui lòng chọn thông tin cần cập nhật!!!", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		
		btnThmKhoa = new JButton("Thêm Khoa [+]");
		btnThmKhoa.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				m_objKhoa.setbFlag(false);
				frmEditKhoa frm = new frmEditKhoa(m_objConnections, m_objSecurityContext, m_objKhoa);
				frm.setVisible(true);
				LoadData(true);
			}
		});
		btnThmKhoa.setIcon(new ImageIcon(frmKhoa.class.getResource("/images/9.png")));
		btnThmKhoa.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnThmKhoa);
		capNhat.setIcon(new ImageIcon(frmKhoa.class.getResource("/images/12.png")));
		capNhat.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(capNhat);

		lamMoi = new JButton("Làm tươi [^]");
		lamMoi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				LoadData(true);
			}
		});

		lamMoi.setIcon(new ImageIcon(frmKhoa.class.getResource("/images/2_3.png")));
		lamMoi.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(lamMoi);

		ghiFile = new JButton("Ghi xuống Files [*]");
		ghiFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] options = { "File XML", "File JSON", "File DAT", "Thoát" };
				int temp = JOptionPane.showOptionDialog(getParent(), "Hãy chọn loại FILE bạn muốn ghi: ",
						"Ghi xuống FILE", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
						options[options.length - 1]);
				if (temp == 0) {
					List<Object> lisField = new ArrayList<Object>();
					List<List<Object>> lisValues = new ArrayList<List<Object>>();
					List<Object> Values = new ArrayList<Object>();
					
					try {
						ResultSet objRs = m_objControllers.ExecOfGetElements();
						
						ResultSetMetaData objMeta = objRs.getMetaData();
						int col = objMeta.getColumnCount();
						
						for (int i = 1; i <= col; i++) {
							lisField.add(objMeta.getColumnName(i));
						}
						
						while(objRs.next()){
							Values = new ArrayList<Object>();
							for (int j = 1; j <=col; j++) {
								Values.add(objRs.getString(j));
							}
							lisValues.add(Values);
						}
						
					} catch (Exception e2) {
						// TODO: handle exception
						e2.getMessage();
					}
					boolean bResult = false;
					// Code...
					
					JFileChooser objFile = new JFileChooser();
			        objFile.setCurrentDirectory(new java.io.File("."));
			        objFile.setDialogTitle("Lưu file: ");
			        objFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			        String[] EXTENSION = new String[] { "xml" };
			        FileNameExtensionFilter filter = new FileNameExtensionFilter("XML files", EXTENSION);
			        objFile.setFileFilter(filter);
			        objFile.setMultiSelectionEnabled(false);

			        int returnVal = objFile.showSaveDialog(null);
			        String ParentPath = "";
			        String FileName = "";
			        if (returnVal == JFileChooser.APPROVE_OPTION) {
			            ParentPath = objFile.getSelectedFile().getParent();
			            FileName = objFile.getSelectedFile().getName();
			            String path = ParentPath+"/"+FileName+".xml";
			            FileIOStreams<KhoaEntity> objFileIo = new FileIOStreams<KhoaEntity>();
			            try {
							bResult = objFileIo.WriteElements(lisField, lisValues, "QUANLYBENHVIEN", "KHOA", path, true);
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							JOptionPane.showMessageDialog(getParent(), "Err: "+e1.getMessage());
						}
			            
			            if(bResult){
			            	JOptionPane.showMessageDialog(getParent(), "Ghi xuống FILE XML thành công!!!", "Thông báo",
									JOptionPane.INFORMATION_MESSAGE);
			            }
			        }
				} else if (temp == 1) {
					// Code...
					JOptionPane.showMessageDialog(getParent(), "Ghi xuống FILE JSON thành công!!!", "Thông báo",
							JOptionPane.INFORMATION_MESSAGE);
				} else if (temp == 2) {
					// Code...
					List<HashMap<String, String>> lisHash = new ArrayList<HashMap<String,String>>();
					HashMap<String, String> hashMap = null;
					
					ResultSet objRs = null;
					ResultSetMetaData objRsData = null;
					
					try {
						objRs = m_objControllers.ExecOfGetElements();
						
						objRsData = objRs.getMetaData();
						
						int col = objRsData.getColumnCount();
						
						while(objRs.next()){
							hashMap = new HashMap<String, String>();
							for(int i=1; i<=col; i++){
								hashMap.put(objRsData.getColumnName(i), objRs.getString(i));
							}
							lisHash.add(hashMap);
						}
					} catch (Exception e2) {
						// TODO: handle exception
						e2.getMessage();
					}
					boolean bResult = false;
					
					JFileChooser objFile = new JFileChooser();
			        objFile.setCurrentDirectory(new java.io.File("."));
			        objFile.setDialogTitle("Lưu file: ");
			        objFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			        String[] EXTENSION = new String[] { "dat" };
			        FileNameExtensionFilter filter = new FileNameExtensionFilter("DAT files", EXTENSION);
			        objFile.setFileFilter(filter);
			        objFile.setMultiSelectionEnabled(false);

			        int returnVal = objFile.showSaveDialog(null);
			        String ParentPath = "";
			        String FileName = "";
			        if (returnVal == JFileChooser.APPROVE_OPTION) {
			            ParentPath = objFile.getSelectedFile().getParent();
			            FileName = objFile.getSelectedFile().getName();
			            String resource = ParentPath+"/";
			            String fileName = FileName+".dat";
			            FileIOStreams<List<HashMap<String, String>>> objFileIo = new FileIOStreams<List<HashMap<String, String>>>();
			            try {
							bResult = objFileIo.WriteListObjects(lisHash, resource, fileName);
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							JOptionPane.showMessageDialog(getParent(), "Err: "+e1.getMessage());
						}
			            
			            if(bResult){
			            	JOptionPane.showMessageDialog(getParent(), "Ghi xuống FILE DAT thành công!!!", "Thông báo",
									JOptionPane.INFORMATION_MESSAGE);
			            }
			        }
				}
			}
		});

		ghiFile.setIcon(new ImageIcon(frmKhoa.class.getResource("/images/13.png")));
		ghiFile.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(ghiFile);

		close = new JButton("Đóng [x]");
		close.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		
		btnXa = new JButton("Xóa [-]");
		btnXa.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(bFlag){
					m_objKhoa.setMaKhoa(String.valueOf(obj_DTM.getValueAt(tableData_1.getSelectedRow(), 0)));
					Object[] options = { "Xóa", "Thoát" };
					int choose = JOptionPane.showOptionDialog(getParent(), "Bạn có thực sự muốn xóa thông tin này?", "Xác nhận",
							JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
							options[options.length - 1]);
					if(choose == 0){
						boolean bResult=false;
						try {
							bResult = m_objControllers.ExecOfDeleteElement(m_objKhoa);
						} catch (Exception e2) {
							// TODO: handle exception
							JOptionPane.showMessageDialog(getParent(), "Err: " + e2.getMessage(), "Thông báo",
	                                JOptionPane.INFORMATION_MESSAGE);
						}
						if(bResult){
							JOptionPane.showMessageDialog(getParent(), "Xóa thông tin thành công!!!", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
						}
					}
					bFlag = false;
				}else{
					JOptionPane.showMessageDialog(getParent(), "Vui lòng chọn thông tin cần xóa!!!", "Thông báo",
							JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		btnXa.setIcon(new ImageIcon(frmKhoa.class.getResource("/images/3.png")));
		btnXa.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnXa);

		close.setIcon(new ImageIcon(frmKhoa.class.getResource("/images/6_3.png")));
		close.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(close);

		scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 49, 739, 262);
		contentPane.add(scrollPane);

		tableData_1 = new JTable();
		tableData_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				bFlag = true;
			}
		});
		tableData_1.setFont(new Font("Cambria", Font.PLAIN, 15));
		tableData_1.setCellSelectionEnabled(true);
		tableData_1.setColumnSelectionAllowed(true);
		tableData_1.setFillsViewportHeight(true);
		scrollPane.setViewportView(tableData_1);
		LoadData(true);
	}

	public void LoadData(boolean DataType) {
		bFlag = false;
		try {
			if (!m_objConnections.isClosed()) {
				ResultSet objRs = null;
				if (DataType) {
					if (m_objControllers == null) {
						m_objControllers = new KhoaControllers(m_objConnections, m_objSecurityContext);
					}
					try {
						objRs = m_objControllers.ExecOfGetElements();
					} catch (Exception e) {
						// TODO: handle exception
						JOptionPane.showMessageDialog(getParent(), "Lỗi: " + e.getMessage(), "Thông báo",
								JOptionPane.ERROR_MESSAGE);
					}
				}
				Controls controls = new Controls();

				try {
					obj_DTM = controls.getModels(objRs);
				} catch (Exception e) {
					// TODO: handle exception
					e.toString();
				}
				tableData_1.setModel(obj_DTM);
			} else
				JOptionPane.showMessageDialog(getParent(), "Không kết nối được với DataBase!!!", "Thông báo",
						JOptionPane.ERROR_MESSAGE);
		} catch (Exception e) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(getParent(), "Lỗi: " + e.getMessage(), "Thông báo",
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
}